package com.puman.watchtrade.fragment.sell;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.assist.LoadedFrom;
import com.puman.watchtrade.MainActivity;
import com.puman.watchtrade.R;
import com.puman.watchtrade.fragment.home.imageLoader.SelectPhotoActivity;
import com.puman.watchtrade.fragment.sell.adapter.GridViewAdapter;
import com.puman.watchtrade.fragment.sell.httpHandler.SellHttpHandler;
import com.puman.watchtrade.fragment.sell.model.SellImg;
import com.puman.watchtrade.fragment.sell.model.SellImgs;
import com.puman.watchtrade.fragment.sell.util.CheckImageLoaderConfiguration;
import com.puman.watchtrade.fragment.sell.util.UniversalImageLoadTool;
import com.puman.watchtrade.fragment.set.LoginFragment;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.GlobalData;

/*
 */
@SuppressLint({ "ValidFragment", "NewApi" })
public class SellFragment extends Fragment implements OnClickListener {

	private View mView;

	/*
	 * UI
	 */
	private TextView backlayout;
	private GridView gridView;
	public SellImgs sellImgs = new SellImgs();
	private EditText connectType;
	private EditText connectName;
	private GridViewAdapter adapter;
	/*
	 * variable
	 */
	private boolean isFromHome = false;// 是否来自首页
	private int imgIndex = 1;
	public static final int SUB_SUC = 0x1;
	public static final int SUB_FAIL = 0x2;
	SellHttpHandler sellHttpHandler = new SellHttpHandler();
	DataResult dataResult = new DataResult();
	private SellFragment sellFragment;

	RelativeLayout topImgLayout;

	RelativeLayout firLayout;

	public SellFragment() {
		// TODO Auto-generated constructor stub
	}

	public SellFragment(boolean isFromHome) {
		this.isFromHome = isFromHome;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		mView = inflater.inflate(R.layout.sell_layout, container, false);
		initView();
		// setData();
		File destDir = new File(Environment.getExternalStorageDirectory()
				+ "/watchtrade/upload/");
		// File destDir = new File(sDir);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		gridView = (GridView) mView.findViewById(R.id.grid);
		return mView;
	}

	int layoutHeight = 0;

	private void initView() {
		sellFragment = this;

		if (isFromHome) {
			mView.findViewById(R.id.main_left_img).setVisibility(View.GONE);
			mView.findViewById(R.id.sold_info).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.main_left_imgbtn).setOnClickListener(this);
		} else {
			mView.findViewById(R.id.sold_info).setVisibility(View.GONE);
			mView.findViewById(R.id.main_left_img).setVisibility(View.VISIBLE);
			mView.findViewById(R.id.main_left_imgbtn).setOnClickListener(
					MainActivity.getInstant().mySetOnClickListener);
		}

		mView.findViewById(R.id.sell_select_img).setOnClickListener(this);
		mView.findViewById(R.id.sell_submit).setOnClickListener(this);

		topImgLayout = (RelativeLayout) mView
				.findViewById(R.id.top_img_relayout);
		connectType = (EditText) mView.findViewById(R.id.connect_content);
		if (GlobalData.userInfo != null) {
			connectType.setText(GlobalData.userInfo.getMobile());
		}
		connectName = (EditText) mView.findViewById(R.id.name_content);
		connectType.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					topImgLayout.setVisibility(View.GONE);
				} else {
					topImgLayout.setVisibility(View.VISIBLE);
				}
			}
		});

		connectName.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					topImgLayout.setVisibility(View.GONE);
				} else {
					topImgLayout.setVisibility(View.VISIBLE);
				}
			}
		});

		mView.findViewById(R.id.sell_layout).setOnClickListener(this);

		final InputMethodManager imm = (InputMethodManager) MainActivity
				.getInstant().getSystemService(Context.INPUT_METHOD_SERVICE);

		firLayout = (RelativeLayout) mView.findViewById(R.id.sell_layout);
		// layoutHeight = firLayout.getHeight();
		// Log.i("curry", "layoutHeight = " + layoutHeight);
		firLayout.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						// if (topImgLayout.isShown())
						// { // 说明键盘是弹出状态
						// Log.i("curry","键盘弹出状态");
						// topImgLayout.setVisibility(View.GONE);
						// } else{
						// Log.i("curry", "键盘收起状态");
						// topImgLayout.setVisibility(View.VISIBLE);
						// }
					}
				});

		loadAnimation();

	}

	private void loadAnimation() {
		// 设置透明度
		AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
		// 设置动画执行的时间
		alphaAnimation.setDuration(1500);
		AnimationSet animationalpha = new AnimationSet(true);

		animationalpha.addAnimation(alphaAnimation);

		mView.findViewById(R.id.sell_select_img_layout).startAnimation(animationalpha);
		mView.findViewById(R.id.sell_select_img_connect_layout).startAnimation(animationalpha);
		mView.findViewById(R.id.sell_submit).startAnimation(animationalpha);
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) v.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
		}
		switch (v.getId()) {
		case R.id.main_left_imgbtn:
			MainActivity.fragmentManager.popBackStack();
			break;
		case R.id.sell_select_img:
			ShowPickDialog();
			break;
		case R.id.sell_submit:
			if (imm.isActive()) {
				imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
			}
			topImgLayout.setVisibility(View.VISIBLE);
			submitSell();
			break;
		case R.id.sell_layout:
			if (imm.isActive()) {
				imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
			}
			topImgLayout.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}

	}

	/*
	 * 提交预约
	 */
	private void submitSell() {
		if (sellImgs.sellimgList.size() == 0) {
			Toast.makeText(MainActivity.getInstant(), "请选择上传图片",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (connectType.getText().length() == 0) {
			Toast.makeText(MainActivity.getInstant(), "请填写联系方式",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (!Gjfun.isPhoneNumberValid(connectType.getText().toString())) {
			Toast.makeText(MainActivity.getInstant(), "请填写正确的联系方式",
					Toast.LENGTH_SHORT).show();
			return;
		}
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(submitSellRunnable);
	}

	private void setGridView() {

		int size = sellImgs.sellimgList.size();

		int length = 100;

		DisplayMetrics dm = new DisplayMetrics();
		MainActivity.getInstant().getWindowManager().getDefaultDisplay()
				.getMetrics(dm);
		float density = dm.density;
		int gridviewWidth = (int) (size * (length + 4) * density);
		int itemWidth = (int) (length * density);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
		gridView.setLayoutParams(params); // 重点
		gridView.setColumnWidth(itemWidth); // 重点
		gridView.setHorizontalSpacing(5); // 间距
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setNumColumns(size); // 重点

		adapter = new GridViewAdapter(sellFragment, MainActivity.getInstant()
				.getApplicationContext(), sellImgs);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				sellImgs.sellimgList.get(position).isSelect = !sellImgs.sellimgList
						.get(position).isSelect;
				adapter.notifyDataSetChanged();
			}
		});
	}

	/**
	 * 选择提示对话框
	 */
	private void ShowPickDialog() {
		new AlertDialog.Builder(MainActivity.getInstant())
				.setTitle("选择图片...")
				.setNegativeButton("相册", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Intent intent = new Intent();
						intent.setClass(MainActivity.getInstant(),
								SelectPhotoActivity.class);
						GlobalData.photoList.clear();
						MainActivity.getInstant().startActivity(intent);

					}
				})
				.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						/**
						 */
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						// 下面这句指定调用相机拍照后的照片存储的路径
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
								.fromFile(new File(Environment
										.getExternalStorageDirectory()
										+ "/watchtrade/upload", "watchtrade"
										+ imgIndex + ".jpg")));

						startActivityForResult(intent, 2);
					}
				}).show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		// 如果是直接从相册获取
		case 1:
			if (data != null) {
				startPhotoZoom(data.getData().toString());
			}

			break;
		// 如果是调用相机拍照时
		case 2:
			// Log.i("curry", "take photo1");
			File temp = new File(Environment.getExternalStorageDirectory()
					+ "/watchtrade/upload/" + "watchtrade" + imgIndex + ".jpg");
			startPhotoZoom("file://"
					+ Environment.getExternalStorageDirectory()
					+ "/watchtrade/upload/" + "watchtrade" + imgIndex + ".jpg");
			break;
		// 取得裁剪后的图片
		case 3:
			/**
			 */
			if (data != null) {
				setPicToView(data);
			}
			break;
		default:
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	// public void startPhotoZoom(Uri uri) {
	public void startPhotoZoom(String uri) {
		/*
		 * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
		 * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
		 */
		SellImg sellImg = new SellImg();
		sellImg.setImageUrl(uri.toString());
		sellImgs.sellimgList.add(0, sellImg);
		// Log.i("curry", "media url:"+MediaStore.EXTRA_OUTPUT);
		for (int i = 0; i < sellImgs.sellimgList.size(); i++) {
			Log.i("curry", "img url:"
					+ sellImgs.sellimgList.get(i).getImageUrl());
		}
		setGridView();
		imgIndex++;
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(photo);

			// ib.setBackgroundDrawable(drawable);
			// iv.setBackgroundDrawable(drawable);
		}
	}

	/*
	 */
	Runnable submitSellRunnable = new Runnable() {
		@Override
		public void run() {
			int what = SUB_FAIL;
			dataResult = sellHttpHandler.subOrder(connectName.getText()
					.toString(), connectType.getText().toString(), sellImgs);
			if (dataResult.flag) {
				what = SUB_SUC;
			}
			sendMessage(what);
		}
	};
	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case SUB_SUC:
				Toast.makeText(MainActivity.getInstant(), "" + dataResult.msg,
						Toast.LENGTH_SHORT).show();
				connectName.setText("");
				connectType.setText("");
				break;
			case SUB_FAIL:
				Toast.makeText(MainActivity.getInstant(), "" + dataResult.msg,
						Toast.LENGTH_SHORT).show();
				break;
			}
			return false;
		}
	};
	Handler handler = new Handler(callback);

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	@Override
	public void onResume() {
		super.onResume();
		for (int i = 0; i < GlobalData.photoList.size(); i++) {
			SellImg sellImg = new SellImg();
			sellImg.setImageUrl("file://"
					+ GlobalData.photoList.get(i).getPath_absolute());
			sellImgs.sellimgList.add(0, sellImg);
		}
		GlobalData.photoList.clear();
		setGridView();
	}

	public static void delete(File file) {
		if (file.isFile()) {
			file.delete();
			return;
		}

		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				delete(childFiles[i]);
			}
			file.delete();
		}
	}
}
